package com.offcn.order.service.impl;

import com.offcn.entity.Result;
import com.offcn.order.entity.Cart;
import com.offcn.order.pojo.OrderItem;
import com.offcn.order.service.CartService;
import com.offcn.sellergoods.feign.GoodsFeign;
import com.offcn.sellergoods.feign.ItemFeign;
import com.offcn.sellergoods.pojo.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    ItemFeign itemFeign;

    @Autowired
    GoodsFeign goodsFeign;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public List<Cart> addCart(List<Cart> cartList, Long itemId, Integer num) {
        //1.根据商品skuid 查询商品
        Result<Item> itemResult = itemFeign.findById(itemId);
        Item item = itemResult.getData();
        if (item == null){
            throw new RuntimeException("商品不存在");
        }
        if (item.getStatus().equals("1")){
            throw new RuntimeException("商品未上架");
        }
        //2.获取商家id
        String sellerId = item.getSellerId();
        //3.根据商家id,查询购物车是否有商家的商品
        Cart cart = this.queryGoodsBySellerId(cartList, sellerId);
        //4.如果购物车列表中不包含该商家的购物车
        if (cart == null){
            //新建一个购物车
            cart = new Cart();
            cart.setSellerId(item.getSellerId());
            cart.setSellerName(item.getSeller());
            OrderItem orderItem = this.createOrderItemList(item,num);
            List list = new ArrayList<>();
            list.add(orderItem);
            cart.setOrderItemList(list);
            //把cart添加到cartList中
            cartList.add(cart);
        }else {
            //如果购物车列表中存在商家的商品
            //判断购物车明细是否存在该商品
            OrderItem orderItem = queryGoodsByItemId(cart.getOrderItemList(),itemId);
            if (orderItem == null){
                //如果没有该商品
                this.createOrderItemList(item,num);
                cart.getOrderItemList().add(orderItem);
            }else {
                //如果有该商品，在原商品基础上增加金额 更改数量
                orderItem.setNum(orderItem.getNum()+num);
                BigDecimal bigDecimal = new BigDecimal(Double.parseDouble(item.getPrice() + "") * num);
                orderItem.setTotalFee(bigDecimal);
                //如果操作后小于0
                if (orderItem.getNum() <= 0){
                    //移除商品
                    cart.getOrderItemList().remove(orderItem);
                }
                //如果数量操作后,orderItemList长度为0,移除商家
                if (cart.getOrderItemList().size() == 0){
                    cartList.remove(cart);
                }
            }

        }
        return cartList;
    }

    private OrderItem queryGoodsByItemId(List<OrderItem> orderItemList, Long itemId) {
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getItemId().longValue() == itemId.longValue()){
                return orderItem;
            }
        }
        return null;
    }

    private OrderItem createOrderItemList(Item item,Integer num) {
        if (num <= 0){
            throw new RuntimeException("数量非法");
        }
        OrderItem orderItem = new OrderItem();
        orderItem.setGoodsId(item.getGoodsId());
        orderItem.setItemId(item.getId());
        orderItem.setNum(num);
        orderItem.setPicPath(item.getImage());
        orderItem.setPrice(item.getPrice());
        orderItem.setSellerId(item.getSellerId());
        orderItem.setTitle(item.getTitle());
        BigDecimal bigDecimal = new BigDecimal(Double.parseDouble(item.getPrice() + "") * num);
        orderItem.setTotalFee(bigDecimal);
        return orderItem;
    }

    private Cart queryGoodsBySellerId(List<Cart> cartList, String sellerId) {
        for (Cart cart : cartList) {
            if (cart.getSellerId().equals(sellerId)){
                return cart;
            }
        }
        return null;
    }

    @Override
    public void saveCart(String username, List<Cart> cartList) {
        System.out.println("存储到redis中");
        redisTemplate.boundHashOps("cartList").put(username,cartList);
    }

    @Override
    public List<Cart> findCartFromRedis(String username) {
        List<Cart> cartList = (List<Cart>) redisTemplate.boundHashOps("cartList").get(username);
        if (cartList == null){
            cartList = new ArrayList<>();
        }
        return cartList;
    }
}
